#include <QLocale>
#include "abstract-database-client.h"
#include "model-result.h"
#include "product-in-warehouse-addition-model.h"
#include "product-in-warehouse-addition-queries.h"

ProductInWarehouseAdditionModel::ProductInWarehouseAdditionModel(QObject *parent) :
    StandardDatabaseModel(parent)
{
}

void ProductInWarehouseAdditionModel::initialize()
{
    m_queries = new ProductInWarehouseAdditionQueries(this);
    m_headerSections << "Nazwa" << "Cena" << "VAT" << "Ilość";
    StandardDatabaseModel::initialize();
}

void ProductInWarehouseAdditionModel::setupInternalModel()
{
    StandardDatabaseModel::setupInternalModel();

    for (int i = 0; i < rowCount(); i++)
    {
        // sum column
        QString price = QLocale().toString(m_internalModel->index(i, PriceColumn+m_idColumnCount).data().toDouble(), 'f', 2);
        m_internalModel->setData(m_internalModel->index(i, PriceColumn+m_idColumnCount), price, Qt::DisplayRole);
    }
}

void ProductInWarehouseAdditionModel::loadData()
{
    ModelResult* result = m_databaseClient->selectModel(m_queries->selectQuery(0, 0));
    connect (result, &ModelResult::resultReady, this, &ProductInWarehouseAdditionModel::continueLoadData);
}

void ProductInWarehouseAdditionModel::continueLoadData (ModelResult* result)
{
    result->deleteLater();
    if (result->hasError())
    {
        emit notifyWarning("Błąd ładowania danych", result->error().text());
        return;
    }

    m_productInWarehouseModel = result->model();
    m_productInWarehouseModel->setParent(this);

    QString selectQuery = m_queries->selectQuery(1, 0);
    ModelResult* newResult = m_databaseClient->selectModel(selectQuery);
    connect (newResult, &ModelResult::resultReady, this, &ProductInWarehouseAdditionModel::continueLoadData2);
}

void ProductInWarehouseAdditionModel::continueLoadData2 (ModelResult* result)
{
    result->deleteLater();
    if (result->hasError())
    {
        emit notifyWarning("Błąd ładowania danych", result->error().text());
        return;
    }

    QAbstractTableModel* productModel = result->model();
    for (int i = 0; i < productModel->rowCount(); i++)
    {
        QVariant id = productModel->index(i, 0).data();
        for (int j = 0; j < m_productInWarehouseModel->rowCount(); j++)
        {
            if (m_productInWarehouseModel->index(j, 2).data() == id)
            {
                productModel->removeRow(i);
                m_productInWarehouseModel->removeRow(j);
                i--;
                break;
            }
        }
    }

    delete m_productInWarehouseModel;

    QVariantList parameters;
    for (int i = 0; i < productModel->rowCount(); i++)
        parameters << productModel->index(i, 0).data();

    QString selectQuery = m_queries->selectQuery(2, parameters.size());
    ModelResult* newResult = m_databaseClient->selectModel(selectQuery, parameters);
    connect (newResult, &ModelResult::resultReady, this, &ProductInWarehouseAdditionModel::finishLoadData);
}
